from flask import Blueprint, request, jsonify
from utils.comm import send_message
from utils.redis import r
import random
import re
from db import db1
from jwt1 import *

bp_auser = Blueprint('adminuser', __name__)


@bp_auser.route('/sendsms',methods=['POST','GET'])
def sendsms():
    if request.method=='GET':
        # 1.接口手机号，有效性验证
        mobile = request.args.get('mobile')
        reg = re.match('^1[3-9]\d{9}$',mobile)
        if reg:
            #先从redis中获取。如果存在 则不发
            value = r.str_get(mobile)
            if value:
                return jsonify(({"code":10011,'mes':'时效还没过'}))
            # 2.随机数生成验证码
            code = random.randint(100000, 999999)
            # 3.调用短信接口发
            flag = send_message(mobile, code, 10)
            if flag:
                # 5.成功redis存储
                r.str_set(mobile, code, 1500)
            else:
                pass
                # 4.失败重新发

            # 6.返回结果
            return jsonify({"code": 200})
        return jsonify({"code": 10010})

    else:
        # 手机号、验证码发起请求 -》根据手机号去redis中取验证码 -》没取到直接返回
        # redis取出来的验证码，输入的对比 -》对比成功 -》去数据库查询 -》手机号存在 -》生成token返回
        mobile = request.args.get('mobile')
        code = request.args.get('code')

        get_mobiel = r.str_get(mobile)
        if get_mobiel:
            if int(get_mobiel)==int(code):
                # 对比成功
                sql = '''select * from admin_user where name="%s"'''%(mobile)
                d = db1.find(sql)
                if d:
                    # 从redis中删除
                    # r.str_del(mobile)
                    # 生成token返回
                    sql1 = '''select roles.id,admin_user.name from roles inner join admin_user on roles.id=admin_user.role_id where roles.id="%s".id'''%(d)
                    sql2 = '''select * from resources as re inner join roles_resource as ro on re.id=resource_id where role_id="%d"'''%(int(sql1.id))
                    data = {'mobile': mobile, 'code': code,'userid':d['id']}
                    m = myjwt.jwt_encode(data)
                    return jsonify({"code": 200,'token':m,"list2":sql2,'list1':sql1})
                else:
                    return jsonify({"code": 10011, "mes": '用户名不存在'})
            else:
                return jsonify({"code": 10012, "mes": '验证码不正确'})
        else:
            return jsonify({"code":10013,"mes":'验证码已经过期，请重新发送'})




